package com.wangsd.web.api;

import com.github.binarywang.wxpay.constant.WxPayConstants;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.wangsd.common.basicbean.Result;
import com.wangsd.common.component.WeixinPayService;
import com.wangsd.common.component.WxPayServiceExt;
import com.wangsd.common.component.extBean.AuthinfoRequest;
import com.wangsd.common.component.extBean.AuthinfoResponse;
import com.wangsd.common.exception.BusinessException;
import com.wangsd.common.utils.ApplicationUtils;
import com.wangsd.web.MyController;
import com.wangsd.web.face.entity.*;
import com.wangsd.web.face.service.DeviceService;
import com.wangsd.web.face.service.MerchantService;
import com.wangsd.web.face.service.StoreService;
import com.wangsd.web.face.service.TOrderService;
import com.wangsd.web.sys.entity.SysUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 安全放行的controller
 */
@Api(value = "depositface", tags = "APP押金对接接口")
@Controller
@RequestMapping("/api/depositface")
@Slf4j
public class DepositApiController extends MyController {

    @Autowired
    TOrderService tOrderService;
    @Autowired
    WeixinPayService weixinPayService;
    @Autowired
    DeviceService deviceService;
    @Autowired
    StoreService storeService;
    @Autowired
    MerchantService merchantService;
    /**
     * 获取调用凭证(
     *
     * @param rawdata  机器授权码
     * @param deviceNo 机器序列号
     * @return
     */
    @ApiOperation(value = "获取设备授权码", notes = "获取设备授权码", httpMethod = "POST")
    @RequestMapping(value = "/getauthcode", method = RequestMethod.POST)
    @ResponseBody
    public Object getWxpayfaceAuthinfo(@RequestParam String rawdata, @RequestParam String deviceNo) {
        try {
            if (StringUtils.isBlank(rawdata) || StringUtils.isBlank(deviceNo)) {
                return Result.fail("参数错误");
            }

            //获取设备信息
            Device device = deviceService.selectByDeviceNo(deviceNo);
            if (device == null) {
                return Result.fail("设备配置未找到，或未注册");
            }
            //获取门店信息
            Store store = storeService.getById(device.getStoreId());
            if (store == null) {
                return Result.fail("设备未分配门店");
            }
            //获取商户信息
            Merchant merchant = merchantService.getById(store.getMerchantId());
            if (merchant == null) {
                return Result.fail("商户信息异常");
            }
            AuthinfoRequest request = new AuthinfoRequest();
            request.setSignType(WxPayConstants.SignType.MD5);
            request.setRawdata(rawdata);
            request.setStoreName(store.getName());
            request.setStoreId(store.getId().toString());
            request.setDeviceId(deviceNo);
            request.setNow((System.currentTimeMillis() + "").substring(0, 10));
            request.setVersion("1");

            request.setSubAppId(merchant.getSubAppId());
            request.setSubMchId(merchant.getSubMchId());
            WxPayServiceExt wxPayServiceExt = weixinPayService.getServiceExt(store.getCode(), merchant.getSubMchId());

            AuthinfoResponse authinfo = wxPayServiceExt.getWxpayfaceAuthinfo(request);

            Map map = new HashMap();
            map.put("appid", authinfo.getAppid());
            map.put("subAppId", merchant.getSubAppId());
            map.put("mchId", authinfo.getMchId());
            map.put("subMchId", authinfo.getSubMchId());
            map.put("storeId", authinfo.getStoreId());
            map.put("authinfo", authinfo.getAuthinfo());
            return Result.success(map);
        } catch (WxPayException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 人脸押金支付
     *
     * @param faceCode   支付人脸识别码
     * @param deviceNo   设备编号
     * @param consumeFee   订单金额
     * @param depositFee  押金
     * @param subOpenId 子商户下的openId
     * @return
     */
    @ApiOperation(value = "人脸押金支付（token验证：header ：Access-Token）", notes = "人脸押金支付（token验证：header ：Access-Token）", httpMethod = "POST")
    @RequestMapping(value = "/paydepositorder", method = RequestMethod.POST)
    @ResponseBody
    public Object paydepositorder(HttpServletRequest request,
                                  @ApiParam(value = "人脸faceCode", required = true)@RequestParam String faceCode,
                                  @ApiParam(value = "设备号", required = true)@RequestParam String deviceNo,
                                  @ApiParam(value = "商户号", required = true)@RequestParam String outTradeNo,
                                  @ApiParam(value = "消费金额", required = true)@RequestParam Integer consumeFee,
                                  @ApiParam(value = "押金金额", required = true)@RequestParam Integer depositFee,
                                  @ApiParam(value = "子商户下的openid", required = true)@RequestParam String subOpenId) {
        SysUser user = getUserInfo();
        if (user == null) {
            return Result.fail("请登录收银员账号！！");
        }
        try {
            TOrder order = tOrderService.createFaceDepositPayOrder(request,faceCode, deviceNo,outTradeNo, consumeFee, depositFee, user.getId(),subOpenId);
            if (order != null && order.getOrderStatus() == 5) {
                return Result.success(order);
            } else {
                return Result.fail("押金支付失败");
            }
        } catch (Exception e) {
            log.error("人脸押金支付（token验证：header ：Access-Token）:" + e.getMessage());
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 退押金
     *
     * @param deviceNo   设备编号
     * @param outTradeNo   商户订单号
     * @param consumeFee   订单金额
     * @return
     */
    @ApiOperation(value = "退押金", notes = "退押金（token验证：header ：Access-Token）", httpMethod = "POST")
    @RequestMapping(value = "/returndeposit", method = RequestMethod.POST)
    @ResponseBody
    public Object returndeposit(HttpServletRequest request,
                                @ApiParam(value = "设备号", required = true)@RequestParam String deviceNo,
                                @ApiParam(value = "商户交易单号", required = true)@RequestParam String outTradeNo,
                                @ApiParam(value = "消费金额", required = true)@RequestParam Integer consumeFee) {
        SysUser user = getUserInfo();
        if (user == null) {
            return Result.fail("请登录收银员账号！！");
        }
        try {
            Deposit deposit = tOrderService.returndeposit(request,outTradeNo, deviceNo, consumeFee, user.getId());
            if (deposit != null && deposit.getDepositStatus() == 1) {
                return Result.success();
            } else {
                return Result.fail("退押金失败");
            }
        } catch (BusinessException e) {
            if(9000==e.getCode()){
                return Result.fail(e.getMsg());
            }else if(9001==e.getCode()){
                return Result.fail(e.getMsg());
            }
            return Result.fail(e.getMessage());
        } catch (Exception e) {
            log.error("退押金（token验证：header ：Access-Token）:" + e.getMessage());
            return Result.fail(e.getMessage());
        }
    }

}
